package com.example.javaweb;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/PurchaseServlet")
public class PurchaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Cake cake = CakeDB.getCakeById(id);
        if(cake == null){
            resp.sendRedirect("ListCakeServlet");
        }else{
            HttpSession session = req.getSession();
            List<Cake> cart = (List<Cake>)session.getAttribute("cart");
            if(cart == null){
                cart = new ArrayList<Cake>();
                session.setAttribute("cart",cart);
            }
            cart.add(cake);
            Cookie cookie = new Cookie("JSESSIONID", session.getId());
            cookie.setMaxAge(60*30);
            resp.addCookie(cookie);
            resp.sendRedirect("success2.jsp");
        }
    }
}
